﻿using UnityEngine;   
using System.Collections;   
using System.Xml;   
using System.Xml.Serialization;   
using System.IO;   
using System.Text;   



public class SaveGameData{
	static SaveGameData instance;
	public static SaveGameData Instance{
		get{
			if (instance == null)
				instance = new SaveGameData ();
			return instance;
		}
	}
	PlayerData _playerData;
	public PlayerData playerData{
		get{
			if(_playerData == null)
				Init();
			return _playerData;
		}
	}
	FileInfo t ;  
	string _data;     
	string m_Version;
	public  string Version {
		set{ m_Version = value;}
		get{ return m_Version;}
	}
	public void Init ()   
	{      
		_playerData = new PlayerData();
		Debug.Log ("Path:"+Application.persistentDataPath+"/"+ "GameData_" + Version + ".xml");
		t = new FileInfo(Application.persistentDataPath+"/"+ "GameData_" + Version + ".xml");   
		LoadXML();
		_playerData.CheckData ();
		Save();  
	}   
	void LoadXML()   
	{   
		if(t.Exists)   
		{   
			StreamReader r = t.OpenText();   
			string _info = r.ReadToEnd();   
			r.Close();   
			_data=_info;   
			if(_data.ToString() != "")   
			{   
				_playerData = (PlayerData)DeserializeObject(_data);                
			}   
		}             
	}   
	public void Save()  
	{       
		_data = SerializeObject(_playerData);   
		StreamWriter writer;   
		if(t.Exists)   
		{   
			t.Delete();    
		}      
		writer = t.CreateText();   
		writer.Write(_data);   
		writer.Close();   
	}     
	string UTF8ByteArrayToString(byte[] characters)   
	{        
		UTF8Encoding encoding = new UTF8Encoding();   
		string constructedString = encoding.GetString(characters);   
		return (constructedString);   
	}   
	
	byte[] StringToUTF8ByteArray(string pXmlString)   
	{   
		UTF8Encoding encoding = new UTF8Encoding();   
		byte[] byteArray = encoding.GetBytes(pXmlString);   
		return byteArray;   
	}   
	
	// Here we serialize our Reward object of reward   
	string SerializeObject(object pObject)   
	{  
		string XmlizedString = null;   
		MemoryStream memoryStream = new MemoryStream();   
		XmlSerializer xs = new XmlSerializer(typeof(PlayerData));   
		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
		xs.Serialize(xmlTextWriter, pObject);   
		memoryStream = (MemoryStream)xmlTextWriter.BaseStream;   
		XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());   
		return XmlizedString;   
	}   
	
	// Here we deserialize it back into its original form   
	object DeserializeObject(string pXmlizedString)   
	{   
		XmlSerializer xs = new XmlSerializer(typeof(PlayerData));   
		MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));   
//		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
		return xs.Deserialize(memoryStream);   
	}   
}